package com.ldq.imooc.basics.dataOperation;

import java.sql.Connection;

/**
 * @Author : 李道泉
 * @Description :
 * @Date : 2018/5/5 16:54
 * @Modified by :
 */
public class TransInfoService {

    public String trans(Account from, Account to, Double amount) throws Exception {

        AccountDao accountDao = new AccountDao();
        TransInfoDao transInfoDao = new TransInfoDao();

        from.setAmount(from.getAmount() - amount);
        accountDao.modify(from);

        to.setAmount(to.getAmount() + amount);
        accountDao.modify(to);

        TransInfo transInfo = new TransInfo();
        transInfo.setSourceAaccount(from.getAccount());
        transInfo.setSourceIid(from.getId());
        transInfo.setDestinationAccount(to.getAccount());
        transInfo.setDestinationId(to.getId());
        transInfo.setAmount(amount);
        transInfoDao.add(transInfo);

        return null;
    }

    public String transaction(Account from, Account to, Double amount) throws Exception {

        Connection conn = DBUtil.getConn();
        conn.setAutoCommit(false);
        try {
            AccountDao accountDao = new AccountDao();
            TransInfoDao transInfoDao = new TransInfoDao();

            from.setAmount(from.getAmount() - amount);
            accountDao.modify(from);

            to.setAmount(to.getAmount() + amount);
            accountDao.modify(to);

            TransInfo transInfo = new TransInfo();
            transInfo.setSourceAaccount(from.getAccount());
            transInfo.setSourceIid(from.getId());
            transInfo.setDestinationAccount(to.getAccount());
            transInfo.setDestinationId(to.getId());
            transInfo.setAmount(amount);
            transInfoDao.add(transInfo);

            conn.commit();
            return "success";
        } catch (Exception e) {
            conn.rollback();
            e.printStackTrace();
            return "fail";
        }
    }
}
